# To change this template, choose Tools | Templates
# and open the template in the editor.

require 'cell'

class Sudoku

  attr_accessor :cells,:properties

  def initialize
    @properties = Hash.new
    @cells = Array.new
    for col in 1..9
      for row in 1..9
        @cells.push(Cell.new(col,row,col+row))
      end
    end
  end
  def clone
    clone = Sudoku.new
    clone.cells = Marshal.load( Marshal.dump(cells) )
    clone.freeze
    clone.cells.freeze
    clone.properties.clear
    clone
  end

  def get(col,row)
    @cells.select{|c| c.column==col && c.row==row}.first
  end

  def cellsInRow(row)
      @cells.select{|c| c.row==row}
  end

  def cellsInColumn(column)
      @cells.select{|c| c.column==column}
  end

  def cellsInGroup(col,row)
      gx = groupId(col)
      gy = groupId(row)
      minx = 3*(gx-1);
			maxx = 3*gx+1;
			miny = 3*(gy-1);
			maxy = 3*gy+1;
      @cells.select { |c|
				c.column>minx && c.column<maxx && c.row>miny && c.row<maxy
			}
  end

  def possibleValues(col,row)
    	values = 1..9
      values = values.reject{|v| cellsInRow(row).collect{|c|c.value}.include?(v)}
      values = values.reject{|v| cellsInColumn(col).collect{|c|c.value}.include?(v)}
      values.reject{|v| cellsInGroup(col,row).collect{|c|c.value}.include?(v)}
  end

  def groupId(position)
      case position
        when 1..3   then   1
        when 4..6  then   2
        when 7..9 then   3
       end

  end

  def unsolvedCells
      @cells.select{|c| c.value==0}
  end

  def solved?
    unsolvedCells.length==0
  end

end
